package com.chain.BrotherExchange.ui.fragment;

import android.support.v7.widget.RecyclerView;

import com.chain.BrotherExchange.R;
import com.chain.BrotherExchange.data.Resource;
import com.chain.BrotherExchange.ui.adapter.LegalTenderDetailsListAdapter;
import com.chain.BrotherExchange.ui.core.AbsNetworkStateFragment;
import com.chain.BrotherExchange.utils.Androids;
import com.chain.BrotherExchange.viewmodel.AssetsDetailsViewModel;
import com.chain.BrotherExchange.viewmodel.core.ViewModelProviders;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import butterknife.Bind;

/**
 * 法币明细列表
 */
public class LegalTenderDetailsListFragment extends AbsNetworkStateFragment implements OnRefreshLoadmoreListener {

    @Bind(R.id.recycler_view) RecyclerView mRecyclerView;
    @Bind(R.id.smart_refresh_layout) SmartRefreshLayout mSmartRefreshLayout;

    private AssetsDetailsViewModel mViewModel;
    private LegalTenderDetailsListAdapter mAdapter;

    @Override
    protected int getLayoutID() {
        return R.layout.simple_load_refresh_recycler_view;
    }

    @Override
    protected void initActions() {
        mViewModel = ViewModelProviders.of(this).get(AssetsDetailsViewModel.class);
        mSmartRefreshLayout.setOnRefreshLoadmoreListener(this);

        mAdapter = new LegalTenderDetailsListAdapter();
        mRecyclerView.setAdapter(mAdapter);

        initLegalTenderDetails();
    }

    private void initLegalTenderDetails() {
        mViewModel.newLegalTenderAssetsDetails().observe(this, resource ->
                Resource.load(getContext(), resource, this, result -> {
                    mAdapter.setOrder(result);
                    mSmartRefreshLayout.finishRefresh();
                })
        );
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        mViewModel.moreLegalTenderAssetsDetails().observe(this, resource -> {
            switch (resource.state) {
                case EMPTY:
                    Androids.makeText(R.string.no_more);
                    break;
                case NOT_NETWORK:
                    Androids.makeText(R.string.network_error);
                    break;
                case ERROR:
                    Androids.makeText(resource.message);
                    break;
                case SUCCESS:
                    mAdapter.addOrder(resource.source);
                    break;
            }

            mSmartRefreshLayout.finishLoadmore(0);
        });
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        initLegalTenderDetails();
    }

    @Override
    public void onAnewRequest() {
        initLegalTenderDetails();
    }
}
